﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using bmapi.Models.DataEntity;
using Jose;

namespace bmapi
{
    public class JwtAuthActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //string pa = actionContext.Request.Headers.Authorization.Parameter;
            var secret = ConfigurationManager.AppSettings["secret"];
            string url = HttpContext.Current.Request.Url.Query;
            string token = url.Substring(url.LastIndexOf("=") + 1);
            if (!string.IsNullOrEmpty(token) && url.IndexOf("token") > -1)
            {
                try
                {
                    var jwtObject = JWT.Decode<JwtAuthObject>(
                        token,
                        Encoding.UTF8.GetBytes(secret),
                        JwsAlgorithm.HS256);
                }
                catch (Exception ex)
                {
                    setErrorResponse(actionContext, ex.Message);
                }
            }
            else
            {
                if (actionContext.Request.Headers.Authorization == null && actionContext.Request.Headers.Authorization.Scheme != "Bearer")
                {
                    setErrorResponse(actionContext, "401 Unauthorized");
                }
                else
                {
                    try
                    {
                        var jwtObject = Jose.JWT.Decode<JwtAuthObject>(
                            actionContext.Request.Headers.Authorization.Parameter,
                            Encoding.UTF8.GetBytes(secret),
                            JwsAlgorithm.HS256);
                    }
                    catch (Exception ex)
                    {
                        setErrorResponse(actionContext, ex.Message);
                    }
                }
            }
            base.OnActionExecuting(actionContext);
        }

        private static void setErrorResponse(HttpActionContext actionContext, string message)
        {
            var response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, message);
            actionContext.Response = response;
        }
    }
}